/*
 * @Description: 
 * @Author: seafwg
 * @Date: 2022-01-06 15:25:24
 * @LastEditTime: 2022-01-06 15:33:44
 * @LastEditors: seafwg
 */
// 数组抽象成树结构：
const nest = (items, id = 0, link = 'parent_id') => items.filter(item => item[link] === id).map(item => ({ ...item, children: nest(items, item.id) }));
let comments = [
  { id: 1, parent_id: 0 },
  { id: 2, parent_id: 1 },
  { id: 3, parent_id: 1 },
  { id: 4, parent_id: 2 },
  { id: 5, parent_id: 4 }
];

// 递归判断
const arr2ArrTree = (arr, pId) => {
  const arrTemp = []
  arr.forEach(item => {
    if(item.parent_id === pId) {
      item.children = arr2ArrTree(arr, item.id)
      arrTemp.push(item)
    }
  })
  return arrTemp;
}

console.log(arr2ArrTree(comments, 0))
console.log(nest(comments))